package com.wml.sellPhone.controller;

import com.wml.sellPhone.pojo.Cart;
import com.wml.sellPhone.pojo.Order;
import com.wml.sellPhone.pojo.OrderDetail;
import com.wml.sellPhone.pojo.User;
import com.wml.sellPhone.service.ICartService;
import com.wml.sellPhone.service.IMobileService;
import com.wml.sellPhone.service.IOrderDetailService;
import com.wml.sellPhone.service.IOrderService;
import com.wml.sellPhone.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车控制器
 *
 * @author Hayes
 * @date 2018-06-28 08:55
 */
@Controller
public class CartController {
    @Autowired
    private ICartService cartService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IMobileService mobileService;

    @Autowired
    private IOrderDetailService orderDetailService;

    /**
     * 删除购物车条目
     * @param id 购物车条目ID
     * @param model
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cart/del", method = RequestMethod.GET)
    public Map delCart(@RequestParam(value = "uid") Long id, Model model, HttpServletRequest request){
        Map<String,String> map = new HashMap<>(1);
        // 根据购物车条目ID判断有没购物车条目的存在
        if (cartService.selectByID(id) == true) {
            // 存在
            // 删除购物车条目ID所在的购物车条目
            boolean result = cartService.deleteItem(id);
            // 查询用户的购物车条目
            List<Cart> cartList = cartService.selectByUserId(request);
            // 设置model属性 购物车条目列表
            model.addAttribute("cartList",cartList);
            // 设置session属性 购物车总条目个数
            request.getSession().setAttribute("cartItemCount",cartList.size());
            if (result == true) {
                map.put("delResult","true");
            } else {
                map.put("delResult","false");
            }
        } else {
            // 不存在
            map.put("delResult","notexist");
        }
        return map;
    }

    /**
     * 根棍购物车条目
     * @param id 购物车条目ID
     * @param quantity 数量
     * @param model
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cart/update", method = RequestMethod.GET)
    public Map updateCart(Long id, Long quantity, Model model,HttpServletRequest request){
        Map<String,String> map = new HashMap<>(1);
        // 根据购物车条目ID判断有没购物车条目的存在
        if (cartService.selectByID(id) == true) {
            // 根据购物车条目ID更新购物车条目数量为quantity
            boolean result = cartService.updateItem(id, quantity);
            // 根据用户ID查询购物车条目
            List<Cart> cartList = cartService.selectByUserId(request);
            // 设置model属性 购物车条目列表
            model.addAttribute("cartList",cartList);
            // 设置session书信 购物车条目总个数
            request.getSession().setAttribute("cartItemCount",cartList.size());
            if (result == true) {
                map.put("updateResult","true");
            } else {
                map.put("updateResult","false");
            }
        } else {
            map.put("updateResult","notexist");
        }
        return map;
    }

    /**
     * 购物车结算
     * @param model
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cart/checkout" , method = RequestMethod.GET)
    public Map checkout(Model model,HttpServletRequest request) {
        Map map = new HashMap(1);
        User user = (User) request.getSession().getAttribute(Constant.USER_INFO);
        if (user != null) {
            /**
             * 订单码的生成
             */
            // 产生2个0-9的随机数
            int r1=(int)(Math.random()*(10));
            int r2=(int)(Math.random()*(10));
            // 一个13位的时间戳
            long now = System.currentTimeMillis();
            // 订单码
            String serialNumber = String.valueOf(r1)
                    + String.valueOf(r2)
                    + String.valueOf(now);

            /**
             * 实例化Order
             */
            Order order = new Order();
            order.setUserid(user.getUserid());
            order.setSerialnumber(serialNumber);
            order.setCreattime(new Date());
            // 设置账单总金额
            order.setCost((Double) request.getSession().getAttribute("cartItemsTotal"));

            if (orderService.save(order)) {
                List<Cart> cartList = cartService.selectByUserId(request);
                for (Cart cart : cartList) {
                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setOrderid(orderService.selectBySerialNumber(order.getSerialnumber()).getId());
                    orderDetail.setPhoneid(cart.getPhoneid());
                    orderDetail.setQuantity(cart.getQuantity());
                    orderDetail.setCost(mobileService.selectItemById(cart.getPhoneid()).getPrice()*cart.getQuantity());
                    if (orderDetailService.save(orderDetail)) {
                        cartService.deleteByUserId(user.getUserid());
                        request.getSession().setAttribute("cartItemCount",0);
                        map.put("checkoutResult","true");
                    } else {
                        map.put("checkoutResult","false");
                    }
                }
            } else {
                map.put("checkoutResult","false");
            }
        } else {
            map.put("checkoutResult","notexist");
        }
        return map;
    }
}
